<template>
    <div class="picking-outbound-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="picking_outbound" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="领料出库编号" style="margin-bottom: 30px;">
                            <el-input v-model="picking_outbound.picking_outbound_code" disabled placeholder="自动获取编号"
                                readonly />
                        </el-form-item>
                        <el-form-item prop="warehouse_code" label="出库仓库" style="margin-bottom: 30px;">
                            <el-select v-model="picking_outbound.warehouse_code" placeholder="请选择出库仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in Weahouse" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="picking_outbound_dept_id" label="领料部门" style="margin-bottom: 30px;">
                            <el-tree-select v-model="picking_outbound.picking_outbound_dept_id" :data="deptOptions"
                                :props="defaultProps" :check-strictly="true" placeholder="请选择领料部门" @change="getUser()">
                                <template #header>
                                    <el-input v-model="deptName" placeholder="搜索领料部门" style="padding: 5px"
                                        @input="getDeptDebounced" />
                                </template>
                            </el-tree-select>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="出库日期" style="margin-bottom: 30px;" prop="create_time">
                            <el-date-picker v-model="picking_outbound.picking_outbound_time" type="date"
                                placeholder="请选择出库日期" :size="size" style="width: 480px;"
                                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" :editable="false"/>
                        </el-form-item>
                        <el-form-item prop="zone_code" label="出库库区" style="margin-bottom: 30px;">
                            <el-select v-model="picking_outbound.zone_code" placeholder="请选择出库库区" @change="handleSzone">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="picking_outbound_rep_id" label="领料人" style="margin-bottom: 30px;">
                            <el-select v-model="picking_outbound.picking_outbound_rep_id" placeholder="请选择领料人">
                                <template #header>
                                    <el-input v-model="userName" placeholder="搜索领料人" style="padding: 5px"
                                        @input="getUserDebounced" />
                                </template>
                                <el-option v-for="item in userOptions" :key="item.user_id" :label="item.user_name"
                                    :value="item.user_id" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">领料产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="productAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="pro_name" label="产品名称" />
                <el-table-column prop="pro_code" label="产品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="measure_id" label="单位">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.measure_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column property="numder" label="库存数量">
                </el-table-column>
                <el-table-column prop="picking_outbound_qty" label="领料数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.picking_outbound_qty" style="width: 75px" :precision="2"
                            :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="location_code" label="库位">
                    <template #default="scope">
                        <span>{{ kwvalue(scope.row.location_code) }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">领料总数量：{{ picking_total_qty }} &nbsp;&nbsp;&nbsp;
                    出库状态：{{ picking_outbound.picking_outbound_status == '0' ? "待出库" : "已出库" }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="proSaleTableVisible" width="930" title="添加领料产品信息">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="proCode" style="width: 240px;margin-right: 20px;" placeholder="请输入产品名称/编号" />
                <el-tree-select v-model="proTypeCode" :data="proTypeOptions" placeholder="请选择产品类型" :props="treeProps"
                    clearable check-strictly style="width: 240px">
                    <template #header>
                        <el-input v-model="proTypeName" placeholder="搜索产品类型" style="padding: 5px"
                            @input="getProTypeDebounced" />
                    </template>
                </el-tree-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="proReaslt">重置</el-button>
                <el-button type="primary" @click="proEedit">
                    查询
                </el-button>
            </div>
        </div>
        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
            textAlign: 'center',
            background: '#f5f7fa',
            fontWeight: 'bold',
            position: 'sticky',
            top: 0
        }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column property="pro_code" label="产品编号" width="180" />
            <el-table-column property="stock_name" label="产品名称" width="200" />
            <el-table-column property="stock_model" label="规格型号" />
            <el-table-column property="dict_code" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.dict_code) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="成本单价" />
            <el-table-column property="numder" label="库存数量">
            </el-table-column>
            <el-table-column property="location_Code" label="库位">
                <template #default="scope">
                    <span>{{ kwvalue(scope.row.location_Code) }}</span>
                </template>
            </el-table-column>
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleConfirmColse">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, inject, watch, toRaw } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';
import { useStore } from 'vuex';

export default {
    setup() {
        const store = useStore();
        const datamax = store.state.PO_UpdeteArray;
        const picking_outbound = reactive({
            picking_outbound_time: "",
            picking_outbound_id: "", //领料出库id
            picking_outbound_code: "", //领料出库编号
            warehouse_code: "", //出库仓库编号
            warehouse_name: "", //出库仓库名称
            zone_code: "", //出库库区编号
            zone_name: "", //出库库区名称
            picking_outbound_rep_id: "", //领料人id
            picking_outbound_dept_id: "", //领料部门
            create_time: "", //出库时间
            picking_outbound_status: "0", //出库状态(0:待出库 1:已出库)
            picking_outbound_audit_status: "0", //审核状态
            update_by: localStorage.getItem('userLName'), //创建人
            del_flag: "0" //删除标志
        })
        const locationOrder = ref([]);//库位信息
        const router = useRouter()
        const Weahouse = ref([]); //仓库信息
        const Warhouse_zone = ref([]); //库区信息
        const Warehouse_location = ref([]) //库位信息
        const deptOptions = ref([])
        const userOptions = ref([])
        const deptName = ref('')
        const userName = ref('')
        const proSaleTableVisible = ref(false)
        const productData = ref([])
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const measureOptios = ref([])
        const proTypeOptions = ref([])
        const proCode = ref('')
        const proTypeCode = ref('')
        const proTypeName = ref('')
        const multipleTableRef = ref(null); // 表格引用
        const selectedProducts = ref([]); // 存储选中的产品
        const selectedTable = ref(null); //表格引用
        const selectedRows = ref([]); //存储选中的数据
        const selectedData = ref([]); // 最终确认选择的数据
        const picking_total_qty = ref(0) //记录领料总数量
        const ruleFormRef = ref(null)
        const rules = reactive({
            create_time: [
                { required: true, message: "出库日期不能为空", trigger: "blur" },
            ], warehouse_code: [
                { required: true, message: "出库仓库不能为空", trigger: "blur" },
            ], zone_code: [
                { required: true, message: "出库库区不能为空", trigger: "blur" },
            ], picking_outbound_dept_id: [
                { required: true, message: "领料部门不能为空", trigger: "blur" },
            ], picking_outbound_rep_id: [
                { required: true, message: "领料人不能为空", trigger: "blur" },
            ]
        });

        onMounted(() => {
            initDataFromStore()
            getMeasure()
            getUser()
            getDept()
            getProType()
            WeahousesSelect()
            kwfuii()
            proFill()
        })

        const safeDayjsToISO = (date) => {
            if (date === null || date === undefined || date === '') return null
            const d = dayjs(date)
            return d.isValid() ? d.toISOString() : null
        }

        // 从store初始化数据
        const initDataFromStore = async() => {
            if (datamax) {
                const rowData = datamax;
                // console.log('从store获取的数据:', rowData);

                Object.assign(picking_outbound, {
                    picking_outbound_time: safeDayjsToISO(rowData.picking_outbound_time) || new Date().toISOString(),
                    picking_outbound_id: rowData.picking_outbound_id,
                    picking_outbound_code: rowData.picking_outbound_code,
                    warehouse_code: rowData.warehouse_code,
                    warehouse_name: rowData.warehouse_name,
                    zone_code: rowData.zone_code,
                    zone_name: rowData.zone_name,
                    picking_outbound_rep_id: rowData.picking_outbound_rep_id,
                    picking_outbound_dept_id: rowData.picking_outbound_dept_id,
                    create_time: rowData.create_time,
                    picking_outbound_status: rowData.picking_outbound_status,
                    picking_outbound_audit_status: rowData.picking_outbound_audit_status,
                    create_by: rowData.create_by,
                    del_flag: rowData.del_flag
                });

                // 加载明细数据
                if (rowData.details && rowData.details.length > 0) {
                    const pi = await Promise.all(
                        rowData.details.map(async (item) => {
                            // const stock_numder = await getInv_Stock(item.pro_code,item.location_code);
                            const stock_numder = await getInv_Stock({
                                code: item.pro_code,
                                locationCode: item.location_code
                            });
                            return {
                                Picking_outbound_details_id: item.picking_outbound_details_id,
                                pro_name: item.pro_name,
                                pro_code: item.pro_code,
                                pro_brand: item.pro_brand,
                                pro_model: item.pro_model,
                                measure_id: item.measure_id,
                                picking_outbound_qty: item.picking_outbound_qty,
                                location_code: item.location_code || '',
                                location_name: item.location_name || '',
                                numder: stock_numder
                            }
                        })
                    );
                    selectedData.value = pi
                    // console.info('处理后的明细数据:', selectedData.value);

                    // 计算总数量
                    picking_total_qty.value = selectedData.value.reduce((total, item) => {
                        return total + Number(item.picking_outbound_qty || 0);
                    }, 0);
                }

                // 加载仓库和库区信息
                if (rowData.warehouse_code) {
                    handleSelectChange(rowData.warehouse_code);
                }
                if (rowData.zone_code) {
                    handleSzone(rowData.zone_code);
                }
            }
        }

        async function getInv_Stock({ code, locationCode }) {
            try {
                const result = await axios.get("http://localhost:5181/api/Db_warehouse/GetInv_StockByCodeLocationCode", {
                    params: { code: code,LocationCode:locationCode },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
                return result.data.stock_numder;
            } catch (err) {
                console.error(err);
                return null;
            }
        }

        watch(selectedData, (newVal) => {
            // console.log(selectedData.value)
            // console.info(newVal)
            //每次计算时清空累加
            picking_total_qty.value = 0
            newVal.forEach(row => {
                //验证领料数量
                if (isNaN(Number(row.picking_outbound_qty))) {
                    ElMessage.warning('领料数量必须是数字');
                    row.picking_outbound_qty = 0;
                }

                // console.info(row.numder)
                // 验证领料数量不能超过可用库存
                if (Number(row.picking_outbound_qty) > row.numder) {
                    ElMessage.warning(`产品 ${row.pro_code} 的领料数量不能超过可用库存 ${row.numder}`);
                    row.picking_outbound_qty = row.numder;
                }

                picking_total_qty.value += Number(row.picking_outbound_qty)
            });
        }, { deep: true });

        // 查询仓库信息
        function WeahousesSelect() {
            axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            }).then((res) => {
                Weahouse.value = res.data;
            }).catch((res) => {
                console.log(res)
            })
        }

        // 选择出库仓库事件触发
        const handleSelectChange = (selectedValue) => {
            const selectedItem = Weahouse.value.find(item => item.warehouse_code === selectedValue);
            if (selectedItem) {
                picking_outbound.warehouse_name = selectedItem.warehouse_name;
            }

            // 根据选择的仓库编码去给库位赋值
            axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
                params: {
                    warehouse_code: selectedValue
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                Warhouse_zone.value = result.data;
            })
        };

        //选择出库库位时触发
        const handleSzone = (value) => {
            const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value)
            if (selectedItemzone) {
                picking_outbound.zone_name = selectedItemzone.zone_name;
            }

            axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
                params: {
                    zone_code: value
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                Warehouse_location.value = result.data;
            }).catch((err) => {
                console.info(err)
            })
        }

        const handleLocationChange = (value, row) => {
            // 找到选中的库位
            const selectedLocation = Warehouse_location.value.find(item => item.location_code == value);
            // 更新当前行的库位信息
            if (selectedLocation) {
                row.location_code = selectedLocation.location_code;
                row.location_name = selectedLocation.location_name;
            } else {
                row.location_code = "";
                row.location_name = "";
            }
        };

        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data.map(item => ({
                    dict_value: item.dict_value,
                    dict_label: item.dict_label
                }));
            }).catch((err) => {
                console.error("获取单位数据失败:", err);
                measureOptios.value = []; // 出错时设为空数组
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row || row === "0") return "无"; // 增加对"0"的判断
            const measure = measureOptios.value.find(item => item.dict_value == row);
            return measure ? measure.dict_label : "无";
        }

        //防抖函数0.5秒后进行查询
        const getDeptDebounced = debounce(getDept, 500);
        function getDept() {
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                params: {
                    name: deptName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        const getUserDebounced = debounce(getUser, 500);
        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                params: {
                    dept: picking_outbound.picking_outbound_dept_id,
                    name: userName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //把二维数据转换为结构数据
        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.dept_id,
                label: item.dept_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }

        const getProTypeDebounced = debounce(getProType, 500);
        function getProType() {
            axios.get("http://localhost:5181/api/Product_Type/GetProduct_Types", {
                params: {
                    currentPage: 0,
                    pageSize: 0,
                    typeName: proTypeName.value,
                    status: '0'
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                proTypeOptions.value = convertToTreeProTypeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        const convertToTreeProTypeOptions = (items) => {
            return items.map(item => ({
                value: item.pro_type_code,
                pro_type_code: item.pro_type_code,
                label: item.pro_type_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeProTypeOptions(item.children)
                    : []
            }))
        }

        function productAdd() {
            proSaleTableVisible.value = true
            kwfuii()
            proFill()
            proCount()
        }

        function proFill() {
            axios.get("http://localhost:5181/api/FG_Picking_Outbound/GetInv_StockAsyncs", {
                params: {
                    Warehouse_Code: picking_outbound.warehouse_code,
                    Zone_Code: picking_outbound.zone_code,
                    pro_code: proCode.value,
                    pro_attribute_id: 0,
                    currentPage: currentPage.value,
                    pageSize: pageSize.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                productData.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //显示库存数量
        function kykcValue(row) {
            if (!row) return "无";
            const parentDept = productData.value.find((sex) => sex.location_Code == row.location_code && sex.pro_code == row.pro_code);
            return parentDept ? parentDept.stock_numder - parentDept.stock_planned_outbound_qty : "无";
        }

        function proCount() {
            axios.get("http://localhost:5181/api/Db_Product/ProductCount", {
                params: {
                    proName: proCode.value,
                    typeCode: proTypeCode.value,
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            proFill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            proFill();
        }

        //查询按钮
        function proEedit() {
            proFill()
            proCount()
        }

        //重置按钮
        function proReaslt() {
            proCode.value = ""
            proTypeCode.value = ""
            proFill()
            proCount()
        }

        //关闭按钮
        function handleConfirmColse() {
            proSaleTableVisible.value = false
            proCode.value = ""
            proTypeCode.value = ""
        }

        // 表格选择变化时的处理函数
        const handleSelectionChange = (val) => {
            selectedProducts.value = val;
        };

        //点击确定存储选择的产品数据
        const handleConfirmSelection = () => {
            selectedData.value = [
                ...selectedData.value,
                ...selectedProducts.value.map(item => ({
                    Picking_outbound_details_id: item.Picking_outbound_details_id || '0',
                    pro_name: item.stock_name || item.pro_name || '',
                    pro_code: item.pro_code || '',
                    pro_brand: item.pro_brand || '',
                    pro_model: item.stock_model || item.pro_model || '',
                    measure_id: item.dict_code,
                    picking_outbound_qty: 0,
                    location_code: item.location_Code,
                    location_name: item.location_Name,
                    numder: item.stock_numder - item.stock_planned_outbound_qty
                }))
            ];
            proSaleTableVisible.value = false;
            multipleTableRef.value.clearSelection();
        };

        //表格选择变化时处理数据
        const handleSelectedChange = (val) => {
            selectedRows.value = val;
        };

        //判断以添加过的产品数据不能再次添加
        const isDisabled = (row) => {
            return !selectedData.value.some(item => item.pro_code === row.pro_code && item.location_code === row.location_Code);
        };

        //移除选中的table控件数据
        const productDel = () => {
            if (selectedRows.value.length === 0) {
                ElMessage.warning('请先选择要移除的数据');
                return;
            }

            // 同时检查 pro_code 和 location_code
            selectedData.value = selectedData.value.filter(
                item => !selectedRows.value.some(
                    selected => 
                        selected.pro_code === item.pro_code && 
                        selected.location_code === item.location_code // 可以添加更多条件
                )
            );

            if (selectedTable.value) {
                selectedTable.value.clearSelection();
            }

            selectedRows.value = [];
        };

        const validateLocations = () => {
            return selectedData.value.every(item => {
                return item.location_code && item.location_name;
            });
        };

        function handleAdd() {
            ruleFormRef.value.validate(async (valid, fields) => {
                if (valid) {
                    if (selectedData.value.length > 0) {
                        try {
                            pickingOutboundAdd();
                        } catch (err) {
                            console.info(err);
                            ElMessage.error('操作失败，请重试');
                        }
                    } else {
                        ElMessage.warning('请选择要添加的产品数据');
                        return;
                    }
                }
            });
        }

        function pickingOutboundAdd() {
            // 1. 构造明细数据，确保measure_id是数字类型
            const fg_Picking_Outbound_DetailsUpdateDtos = selectedData.value.map(item => ({
                Picking_outbound_details_id: item.Picking_outbound_details_id || '0',
                picking_outbound_code: picking_outbound.picking_outbound_code || '',
                picking_outbound_id: picking_outbound.picking_outbound_id || '0',
                pro_name: item.pro_name || '',
                measure_id: item.measure_id,
                pro_brand: item.pro_brand || '',
                pro_model: item.pro_model || '',
                Pro_code: item.pro_code,
                picking_outbound_qty: Number(item.picking_outbound_qty) || 0,
                location_code: item.location_code || '',
                location_name: item.location_name || ''
            }));

            // 2. 构造主表数据，确保所有字段都有默认值
            const fg_Picking_Outbound_UpdateDto = {
                picking_outbound_id: picking_outbound.picking_outbound_id || 0,
                picking_outbound_code: picking_outbound.picking_outbound_code || '',
                warehouse_code: picking_outbound.warehouse_code || '',
                warehouse_name: picking_outbound.warehouse_name || '',
                zone_code: picking_outbound.zone_code || '',
                zone_name: picking_outbound.zone_name,
                picking_outbound_rep_id: Number(picking_outbound.picking_outbound_rep_id) || 0,
                picking_outbound_dept_id: Number(picking_outbound.picking_outbound_dept_id) || 0,
                picking_outbound_time: picking_outbound.picking_outbound_time,
                picking_outbound_status: picking_outbound.picking_outbound_status || '0',
                picking_outbound_audit_status: picking_outbound.picking_outbound_audit_status || '0',
                update_by: localStorage.getItem('userLName'),
                update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                del_flag: picking_outbound.del_flag || '0'
            };

            // 3. 构造完整的请求体
            const requestData = {
                FG_Picking_Outbound_UpdateDto: fg_Picking_Outbound_UpdateDto,
                fg_Picking_Outbound_DetailsUpdateDtos: fg_Picking_Outbound_DetailsUpdateDtos
            };

            // 4. 打印请求数据（调试用）
            // console.log("完整请求数据：", JSON.stringify(requestData, null, 2));

            // 5. 发送请求
            axios.put(
                "http://localhost:5181/api/FG_Picking_Outbound/PutFg_Picking_OutboundUpdate",
                requestData,
                {
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    transformRequest: [(data) => {
                        // 确保空值转换为null而不是undefined
                        return JSON.stringify(data, (key, value) =>
                            value === undefined ? null : value
                        );
                    }]
                }
            ).then((result) => {
                if (result.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '领料出库单更新成功！'
                    });
                    handleClose();  // 关闭弹窗或重置表单
                } else {
                    ElMessage.error('操作未生效，请检查数据');
                }
            }).catch((err) => {
                console.error("详细错误信息：", err.response?.data || err.message);
                ElMessage.error(`保存失败: ${err.response?.data?.title || err.message}`);
            });
        }

        const closeTab = inject('closeTab'); // 注入关闭方法
        function handleClose() {
            const targetPath = "/main/FG/Picking";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "领料出库",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        //查询库位信息
        function kwfuii() {
            axios.get('http://localhost:5181/api/Db_warehouse_location/Warehouse_locationfY', {
                params: {
                    zone_code: picking_outbound.zone_code,
                    currentPage: 1,
                    pageSize: 99
                }, headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                locationOrder.value = result.data;
            }).catch((err) => {
                console.error(err);
            });
        }

        //从库位编号转换为库位昵称
        function kwvalue(row) {
            if (!row) return "无";
            const parentDept = locationOrder.value.find((sex) => sex.location_code == row);
            return parentDept ? parentDept.location_name : "无";
        }

        function zsjvaljue(row) {
            // 假设 row 是一个对象，包含 pro_type_code 字段
            const numder = row.stock_numder - row.stock_planned_outbound_qty
            return numder
        }

        return {
            picking_outbound, handleSelectChange, handleSzone, handleLocationChange, Weahouse, Warehouse_location, Warhouse_zone,
            getDeptDebounced, getUserDebounced, deptOptions, userOptions, deptName, userName, getUser, proSaleTableVisible, productAdd,
            currentPage, pageSize, pageCount, productData, measureOptios, measureValue, proTypeOptions, proCode, proTypeCode, getProTypeDebounced,
            handleSizeChange, handleCurrentChange, proTypeName, proEedit, proReaslt, handleConfirmColse, handleSelectionChange,
            handleConfirmSelection, handleSelectedChange, isDisabled, multipleTableRef, selectedProducts, selectedRows, selectedData, selectedTable,
            productDel, picking_total_qty, ruleFormRef, rules, handleAdd, validateLocations, handleClose,
            kwfuii, kwvalue, locationOrder, zsjvaljue, kykcValue
        }
    }
}
</script>

<style scoped>
.picking-outbound-form {
    padding: 20px;
    background-color: #fff;
    margin-top: -40px;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-top: -20px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>